//
//  ENChoosePhotoManager.m
//  guangebao
//
//  Created by Kuke on 2021/10/11.
//  Copyright © 2021 易联通达. All rights reserved.
//

#import "ENChoosePhotoManager.h"
//调用系统相机，引入头文件：
#import <AVFoundation/AVFoundation.h>
//调用系统相册，引入头文件：
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

#import "XLPhotoIDCardVC.h"

@implementation ENChoosePhotoConfig

- (instancetype)init{
    
    if (self = [super init]) {
        self.chooseType = 0;
        self.isChangeOriginalSize = NO;
        self.changeOriginalSize = CGSizeZero;
        self.changeScale = 0;
        
    }
    
    return self;
}

- (instancetype)initIsChangeOriginalSize:(BOOL)isChangeOriginalSize changeOriginalSize:(CGSize)changeOriginalSize changeScale:(CGFloat)changeScale{
    
    if (self = [super init]) {
        self.isChangeOriginalSize = isChangeOriginalSize;
        self.changeOriginalSize = changeOriginalSize;
        self.changeScale = changeScale;
    }
    
    return self;
}

- (instancetype)initChooseType:(NSInteger)chooseType IsChangeOriginalSize:(BOOL)isChangeOriginalSize changeOriginalSize:(CGSize)changeOriginalSize changeScale:(CGFloat)changeScale{
    
    if (self = [super init]) {
        self.chooseType = chooseType;
        self.isChangeOriginalSize = isChangeOriginalSize;
        self.changeOriginalSize = changeOriginalSize;
        self.changeScale = changeScale;
    }
    
    return self;
}

@end

@interface ENChoosePhotoManager ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)ENChoosePhotoConfig *photoConfig;
@property(nonatomic,copy)ENChoosePhotoManagerBackSingleImageBlock backSingleImageBlock;
@property(nonatomic,strong)UIImagePickerController *imagePickerController;

@end

static ENChoosePhotoManager * _manager;

@implementation ENChoosePhotoManager

///选择相册和相机
+ (instancetype)chooseSingleImageVC:(UIViewController*)currentVc
                photoConfig:(ENChoosePhotoConfig*)photoConfig
       backSingleImageBlock:(ENChoosePhotoManagerBackSingleImageBlock)backSingleImageBlock{
    
    ENChoosePhotoManager *manager = [ENChoosePhotoManager new];
    manager.backSingleImageBlock = backSingleImageBlock;
    manager.photoConfig = photoConfig;
    
    _manager = manager;//把当前的实例对象，赋值给静态变量，防止释放
    
    if (photoConfig.chooseType == 0) {//
        [manager popAllertController:currentVc];
    }else if (photoConfig.chooseType == 1){
        [manager checkAlbumPermission:currentVc];
    }else if (photoConfig.chooseType == 2){
        [manager checkCameraPermission:currentVc];
    }else if (photoConfig.chooseType == 3) {
        [manager openIDCardPhotoWithParentVC:currentVc];
    }
    return manager;
}

-(void)hiddenManager{
    _manager = nil; // 置空静态变量
}

-(void)dealloc {
    NSLog(@"-----销毁");
}

#pragma mark - 选择是相机还是相册

- (void)popAllertController:(UIViewController*)currentVc{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *cremaAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ELog(@"相册");
        [self checkAlbumPermission:currentVc];
    }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ELog(@"相机");
        [self checkCameraPermission:currentVc];
    }];
    @try {
        //修改按钮标题颜色
        [cancelAction setValue:[UIColor enAppViewSubColor] forKey:@"titleTextColor"];
        [cremaAction setValue:[UIColor enAppThemeColor] forKey:@"titleTextColor"];
        [photoAction setValue:[UIColor enAppThemeColor] forKey:@"titleTextColor"];
    } @catch (NSException *exception) {
        ELog(@"获取颜色属性失败了，不能更改颜色了");
    }
    
    
    [alert addAction:cremaAction];
    [alert addAction:photoAction];
    [alert addAction:cancelAction];
    [currentVc presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 相册
- (void)checkAlbumPermission:(UIViewController*)currentVc {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined) {//
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (status == PHAuthorizationStatusAuthorized) {
                            [self selectAlbum:currentVc];
                        }
                    });
                }];
    } else if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
        [self alertAlbum:currentVc];
        
    } else {
        [self selectAlbum:currentVc];
    }
}
- (void)selectAlbum:(UIViewController*)currentVc {
    //判断相册是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
            self.imagePickerController.navigationBar.translucent = NO;
            [currentVc presentViewController:self.imagePickerController animated:YES completion:nil];
        });
    }
}
- (void)alertAlbum:(UIViewController*)currentVc {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请在设置-隐私中打开相册访问权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [currentVc dismissViewControllerAnimated:YES completion:nil];
        [self hiddenManager];
    }];
    [alert addAction:cancel];
    [currentVc presentViewController:alert animated:YES completion:nil];
}


#pragma mark - 相机
- (void)checkCameraPermission:(UIViewController*)currentVc {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                [self takePhoto:currentVc];
            }
        }];
    } else if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
         [self alertCamear:currentVc];
        ELog(@"status==%ld需打开相机访问权限",(long)status);
    } else {
        [self takePhoto:currentVc];
    }
}

- (void)takePhoto:(UIViewController*)currentVc {
    //判断相机是否可用，防止模拟器点击【相机】导致崩溃
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            self.imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
            self.imagePickerController.navigationBar.translucent = NO;
            [currentVc presentViewController:self.imagePickerController animated:YES completion:nil];
        });
    } else {
        ELog(@"不能使用模拟器进行拍照");
    }
}

-(void)alertCamear:(UIViewController*)currentVc {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请在设置中-隐私中打开相机访问权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [currentVc dismissViewControllerAnimated:YES completion:nil];
        [self hiddenManager];
    }];
    [alert addAction:cancel];
    [currentVc presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 身份证拍照
-(void)openIDCardPhotoWithParentVC:(UIViewController *)vc {
    
    XLPhotoIDCardVC * pVC = [XLPhotoIDCardVC new];
    pVC.modalPresentationStyle = UIModalPresentationFullScreen;
    __weak typeof(self) weakSelf = self;
    pVC.photoImageHandle = ^(BOOL isSuccess, UIImage * _Nullable image) {
        if (isSuccess) {
            [weakSelf handleSelectImage:image];
        }
        [weakSelf hiddenManager];
    };
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [vc presentViewController:pVC animated:YES completion:nil];
                });
            }
        }];
    } else if (status == AVAuthorizationStatusDenied || status == AVAuthorizationStatusRestricted) {
         [self alertCamear:vc];
    } else {
        [vc presentViewController:pVC animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    /**
     1.翻转和压缩图片会消耗时间，用异步线程
     2.如果该图片大于2M，会自动旋转90度；否则不旋转
     3.压缩图片到0.1倍  几乎不损失图片质量
     */
//    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self handleSelectImage:image];
        });
    });
    [self hiddenManager];
}

#pragma mark - 图片处理
-(void)handleSelectImage:(UIImage *)image {
    
    UIImage *changeImage;
    if (self.photoConfig.isChangeOriginalSize) {
        changeImage = [self compressOriginalImage:image toSize:self.photoConfig.changeOriginalSize];
    }else{
        changeImage = image;
    }
    
    NSData *changeData;
    if (self.photoConfig.changeScale > 0 || self.photoConfig.changeScale < 1) {
        changeData = UIImageJPEGRepresentation(changeImage, self.photoConfig.changeScale);
    }else{
        changeData = UIImageJPEGRepresentation(changeImage, 1);
    }
    
    // 这里可以增加 压缩图片数据到多大，后期可加
    
    if (self.backSingleImageBlock) {
        self.backSingleImageBlock(changeImage, changeData);
    }
}

-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size
{
    if([[UIScreen mainScreen] scale] == 2.0)
    {
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else if([[UIScreen mainScreen]scale] == 3.0)
    {
        UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    }else
    {
        
        UIGraphicsBeginImageContext(size);
        
    }
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

//图片质量压缩到某一范围内，如果后面用到多，可以抽成分类或者工具类,这里压缩递减比二分的运行时间长，二分可以限制下限。
- (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return resultImage;
}

#pragma mark - 懒加载
- (UIImagePickerController *)imagePickerController {
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self; //delegate遵循了两个代理
        _imagePickerController.navigationBar.translucent = NO;//去除毛玻璃遮挡效果

    }
    return _imagePickerController;
}

@end
